package cn.feizhu.aimarket.ai.workflow.node;

import cn.feizhu.aimarket.ai.workflow.model.constant.WorkflowControlConstant;
import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.action.EdgeAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 人类反馈调度器
 * 根据人类反馈结果决定工作流的下一步
 *
 * @author feizhu
 * @since 2025/10/16
 */
public class HumanFeedbackDispatcher implements EdgeAction {

    private static final Logger logger = LoggerFactory.getLogger(HumanFeedbackDispatcher.class);

    @Override
    public String apply(OverAllState state) {
        logger.info("=== 人类反馈调度器开始执行 ===");

        try {
            // 获取反馈结果
            String feedbackResult = (String) state.value(WorkflowControlConstant.FEEDBACK_RESULT)
                    .orElse("UNKNOWN");

            logger.info("反馈结果: {}", feedbackResult);

            String nextBranch;
            switch (feedbackResult) {
                case "APPROVED":
                    nextBranch = WorkflowControlConstant.BRANCH_CONTINUE;
                    logger.info("大纲已通过审核，继续执行多文档生成");
                    break;
                case "NEEDS_REVISION":
                    nextBranch = WorkflowControlConstant.BRANCH_RETRY;
                    logger.info("大纲需要修改，返回重新生成");
                    break;
                default:
                    nextBranch = WorkflowControlConstant.BRANCH_RETRY;
                    logger.warn("未知的反馈结果，默认返回重新生成: {}", feedbackResult);
                    break;
            }

            return nextBranch;

        } catch (Exception e) {
            logger.error("人类反馈调度器执行异常", e);
            return "BRANCH_RETRY"; // 异常情况下默认重试
        } finally {
            logger.info("=== 人类反馈调度器执行完成 ===");
        }
    }
}
